package com.tuyou.springboot.mybatis.service.impl;

import com.tuyou.springboot.comon.po.User;
import com.tuyou.springboot.mybatis.mapper.UserMapper;
import com.tuyou.springboot.mybatis.service.UserService;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public List<User> getUserByIds(String...ids) {
        List<User> users = new ArrayList<>(ids.length);
        for (String id : ids) {
            users.add(getUserById(Integer.parseInt(id)));
        }
        return users;
    }

    @Transactional(propagation = Propagation.NEVER)
    @Override
    public User getUserById(long id) {
        User user = userMapper.getById(id);
        if (user == null) {
            throw new NullPointerException();
        }
        return user;
    }

    @Override
    public List<User> getAllUser() {
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(new DefaultTransactionDefinition());
        List<User> all = userMapper.getAll();
        dataSourceTransactionManager.commit(transaction);
        return all;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void saveUser(User user) {
        userMapper.save(user);
        System.out.println("service1 :" + user.getId());
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public int updateUser(User user) {
        int update = userMapper.update(user);
        if (update == 0) {
            throw new NullPointerException();
        }
        return update;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public int delUser(long id) {
        int delete = userMapper.delete(id);
        if (delete > 0) {
            throw new NullPointerException();
        }
        return delete;
    }
}